<!--
 * @Description: 
 * @Version: 2.0
 * @Autor: zhangjx
 * @Date: 2023-05-30 11:43:25
 * @LastEditors: uphldjx 1373577124@qq.com
 * @LastEditTime: 2024-07-10 17:51:28
-->
<template>
	<div>
		<div class="flex">
			<el-button type="danger" @click="handleRefresh" v-if="refreshBtn" style="margin-right: 15px">列表刷新</el-button>
			<el-input v-model="query" :placeholder="placeholder" @input="onQueryChanged" class="mr8" />
		</div>
		<el-scrollbar max-height="75vh">
			<el-tree
				ref="treeRef"
				class="mt10"
				:data="treeData"
				node-key="administrationId"
				draggable
				:allow-drop="allowDrop"
				:filter-node-method="filterMethod"
				:props="defaultProps"
				:default-expanded-keys="defaultCheckedKeys"
				highlight-current
				:expand-on-click-node="false"
				@node-click="(e) => handleOperate('detail', e, '详情')"
				@node-drag-start="dragStart"
				@node-drop="handleDrop"
			>
				<template #default="{ node, data }">
					<span class="custom-tree-node w-100" @mouseenter="onMouseenter(node, data)" @mouseleave="onMouseleave(node, data)">
						<span
							:class="!data.disabled && (paramsObj.classifyId == 4 || paramsObj.classifyId == 5) ? 'tree-node-label' : ''"
							:style="{
								color: node.data.administrationId === currentId ? '#1f5aff' : '',
								'margin-right': '10px',
							}"
						>
							<span v-if="node.data.userType" :class="`text-color-${node.data.userType}`"> ({{ orgTypeStrObj[node.data.userType] }}) </span>
							{{ node.label }}
							<!-- <span v-show="(data.regionGrade == 1 || data.regionGrade == 4) && paramsObj.classifyId == 3" style="color: #999; font-size: 14px">
								民政局
							</span> -->
						</span>
						<span v-show="data.show && paramsObj.classifyId == 3">
							<template v-if="data.administrationId !== -1">
								<el-button type="primary" text @click.stop="handleOperate('edit', data, node)" v-auth="'sysadministrationapprover_update'">
									<icon-file-editing-one theme="outline" fill="#333" />
									编辑
								</el-button>
								<el-button type="primary" text v-auth="'sys_user_area_move'">
									<icon-drag theme="outline" fill="#333" />
									移动
								</el-button>
							</template>
							<template v-else>
								<el-button type="primary" text @click.stop="handleOperate('add', data, '添加下级')">
									<icon-add-subset theme="outline" fill="#333" />
									添加下级
								</el-button>
							</template>
						</span>
					</span>
				</template>
			</el-tree>
		</el-scrollbar>
	</div>
</template>

<script setup lang="ts">
import apiMod from '@/apiMod/index'
import { useCrudStore } from '@/stores/crud'
import { useCommonStore } from '@/stores/common'
import { arrayTransTree } from '@/utils/util'
import { ElMessage, ElLoading } from 'element-plus'

const { setAreaTreeData } = useCrudStore()
const emit = defineEmits(['tree-load', 'change'])
const query = ref('')
const treeData = ref([])
const treeRef = ref()
const currentId = ref()
const defaultCheckedKeys = ref([])
const props = withDefaults(
	defineProps<{
		api?: string | number
		placeholder?: string
		paramsObj?: any
		refreshBtn?: boolean
	}>(),
	{
		refreshBtn: true,
	}
)

const { setTreeRefreshData } = useCommonStore()
const { treeRefreshData } = storeToRefs(useCommonStore())

const orgTypeStrObj = {
	1: '机构',
	3: '服务设施',
	2: '运营单位',
}
const defaultProps = {
	value: props.paramsObj.classifyId == 4 ? 'treeKey' : 'administrationId',
	label: 'administrationName',
	children: 'children',
}

const onQueryChanged = (query: string) => {
	treeRef.value!.filter(query)
}
const filterMethod = (value: string, data: any) => {
	if (!value) return true
	return data.administrationName.includes(value)
}

const dragStart = (node) => {
	currentId.value = node.data.id
}
const allowDrop = (dragNode, dropNode, type) => {
	const dgData = dragNode.data,
		dpData = dropNode.data
	return dgData.level === dpData.level && dpData.parentId === dgData.parentId && type !== 'inner'
}

const typeConfig = ref(1)

const getInitData = async () => {
	const formateData = (areaData) => {
		const arr = areaData.map((item) => {
			item.treeKey = item.organizationId || item.administrationId
			item.administrationName = item.administrationName || item.organizationName
			item.treePid = item.administrationPid
			item.disabled = item.organizationId ? false : true
			return item
		})
		const data = arrayTransTree(arr, 'treeKey', 'treePid')
		treeData.value = data
		const checkedKeys = treeData.value.map((item) => {
			const ids = item.children.map((v) =>  v.administrationId||v.treeKey)
			return item.administrationLevel >= 3 ? [item.administrationId] : [...ids, item.administrationId]
		})

		defaultCheckedKeys.value = checkedKeys.flat()
	}
	if (props.paramsObj.classifyId == 4) {
		apiMod.sysServiceOrganization({ type: typeConfig.value }).then((res) => {
			if (res.code == 0 && res.data) {
				formateData(res.data)
				return Promise.resolve('ok')
			}
		})
	} else if (props.paramsObj.classifyId == 5) {
		apiMod.view_serviceprovider_user({ type: typeConfig.value }).then((res) => {
			if (res.code == 0 && res.data) {
				formateData(res.data)
				return Promise.resolve('ok')
			}
		})
	} else {
		apiMod[props.api]({ type: typeConfig.value }).then((res) => {
			if (res.code == 0 && res.data) {
				if (Array.isArray(res.data)) {
					treeData.value = res.data
				} else {
					treeData.value = JSON.parse(res.data)
				}

				const checkedKeys = treeData.value.map((item) => {

					const ids = item.children.map((v) => v.id)
					return item.regionGrade >=3 ? [item.administrationId] :[...ids, item.id]
				})
				defaultCheckedKeys.value = checkedKeys.flat()
				setAreaTreeData(treeData.value)
				emit('tree-load', treeData.value)
				return Promise.resolve('ok')
			}
		})
	}
}

const pageReload: any = inject('reload')
const handleRefresh = () => {
	typeConfig.value = 0
	getInitData().then((res) => {
		pageReload()
		setTreeRefreshData(props.paramsObj.classifyId)
	})
}

const handleDrop = (draggingNode, dropNode, dropType) => {
	const dragSort = draggingNode?.data?.administrationSorting
	const dropSort = dropNode.data.administrationSorting
	let administrationSorting = ''
	if (dropType === 'before') {
		administrationSorting = dropSort
	} else {
		administrationSorting = dragSort
	}
	// 更新数据
	apiMod
		.admin_sysadministration_edit({
			...draggingNode?.data,
			administrationSorting,
		})
		.then((res) => {
			ElMessage.success('调整成功')
			getInitData()
		})
}

const onMouseenter = (node, data) => {
	data.show = true
}
const onMouseleave = (node, data) => {
	data.show = false
}
const handleOperate = (type, data, title) => {
	emit('change', type, data, title)
}

const appendNode = (data, newChild) => {
	newChild.children = []
	if (!data.children) {
		data.children = []
	}
	data.children.push(newChild)
	treeData.value = [...treeData.value]
}

onMounted(() => {
	getInitData()
	if (!props.refreshBtn) {
		return
	}
	// 判断是不是第一次调用
	if (props.paramsObj.classifyId == 4 && !treeRefreshData.value.FWZZ_user) {
		handleRefresh()
	} else if (props.paramsObj.classifyId == 1 && !treeRefreshData.value.DZ_user) {
		handleRefresh()
	} else if (props.paramsObj.classifyId == 3 && !treeRefreshData.value.ZW_user) {
		handleRefresh()
	}
})
defineExpose({
	appendNode,
})
</script>

<style scoped lang="scss">
.text-color-1 {
	color: #f88126;
}
.text-color-2 {
	color: #409eff;
}
.text-color-3 {
	color: #fb4120;
}
.tree-operate {
	visibility: var(--visibility);
}

.custom-tree-node {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

// .tree-node-label {
// 	color: #878789;
// 	position: relative;

// 	&::before {
// 		content: '';
// 		position: absolute;
// 		top: 30%;
// 		left: -15px;
// 		width: 10px;
// 		height: 10px;
// 		background: #ffffff;
// 		border-radius: 50%;
// 		border: 2px solid #1677ff;
// 	}
// }
</style>
